<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="navbar">
			<view class="back-btn" @click="navigateBack">
				<uni-icons type="left" size="24" color="#333"></uni-icons>
			</view>
			<view class="title">{{ customerName }}</view>
			<view class="right-space" @click="handleSessionInfo">
				<uni-icons type="info" size="20" color="#333"></uni-icons>
			</view>
		</view>

		<!-- 聊天内容区域 -->
		<view class="chat-content" ref="chatContentRef">
			<!-- 无消息提示 -->
			<view class="empty-tip" v-if="messageList.length === 0 && !loading">
				<image src="/static/images/empty-chat.png" class="empty-img"></image>
				<text class="empty-text">暂无聊天记录</text>
			</view>

			<!-- 消息列表 -->
			<view v-for="(msg, index) in messageList" :key="index" class="message-item">
				<!-- 客服消息 -->
				<view class="customer-message" v-if="msg.customerMessageSenderType === 3">
					<image :src="customerAvatar" class="sender-avatar"></image>
					<view class="message-bubble customer-bubble">
						<!-- 文本消息 -->
						<view class="message-content" v-if="msg.customerMessageType === 1">
							{{ msg.customerMessageContent }}
						</view>
						<!-- 图片消息 -->
						<image :src="msg.customerMessageImageUrl" class="message-image" mode="widthFix"
							v-if="msg.customerMessageType === 2" @click="previewImage(msg.customerMessageImageUrl)">
						</image>
						<!-- 消息时间 -->
						<view class="message-time">{{ formatTime(msg.customerMessageCreateTime) }}</view>
					</view>
				</view>

				<!-- 用户消息 -->
				<view class="user-message" v-if="msg.customerMessageSenderType === 2">
					<view class="message-bubble user-bubble">
						<!-- 文本消息 -->
						<view class="message-content" v-if="msg.customerMessageType === 1">
							{{ msg.customerMessageContent }}
						</view>
						<!-- 图片消息 -->
						<image :src="msg.customerMessageImageUrl" class="message-image" mode="widthFix"
							v-if="msg.customerMessageType === 2" @click="previewImage(msg.customerMessageImageUrl)">
						</image>
						<!-- 消息时间 -->
						<view class="message-time">{{ formatTime(msg.customerMessageCreateTime) }}</view>
					</view>
					<image :src="userAvatar" class="sender-avatar"></image>
				</view>
			</view>

			<!-- 加载中提示 -->
			<view class="loading-tip" v-if="loading">
				<uni-loading-icon size="24" color="#999"></uni-loading-icon>
				<text class="loading-text">加载中...</text>
			</view>
		</view>

		<!-- 输入区域（会话活跃时） -->
		<view class="chat-footer" v-if="sessionStatus === 0">
			<view class="tool-bar">
				<!-- 图片选择 -->
				<view class="tool-item" @click="chooseImage">
					<uni-icons type="image" size="24" color="#666"></uni-icons>
				</view>
			</view>
			<view class="input-area">
				<textarea v-model="messageContent" placeholder="请输入消息内容..." class="message-input" @confirm="sendMessage"
					@input="autoResizeInput" :style="{height: inputHeight + 'px'}"></textarea>
				<button class="send-btn" @click="sendMessage" :disabled="!messageContent.trim()">
					发送
				</button>
			</view>
		</view>

		<!-- 会话结束提示 -->
		<view class="chat-footer ended" v-if="sessionStatus === 1">
			<uni-icons type="info-circle-o" size="16" color="#999" class="ended-icon"></uni-icons>
			<text class="ended-text">会话已结束，无法发送消息</text>
			<button class="restart-btn" @click="restartSession">重新发起会话</button>
		</view>
	</view>
</template>

<script>
	import SockJS from 'sockjs-client'
	import Stomp from 'stompjs'
	import token from '@/utils/token.js'
	// 引入封装的聊天接口
	import { 
		createSession, 
		endSession, 
		getCustomerMessageList, 
		uploadChatImage 
	} from '@/api/chat'

	export default {
		name: "customerchat",
		data() {
			return {
				// 会话基础信息
				sessionId: '',
				customerId: '',
				customerName: '在线客服',
				customerAvatar: '/static/images/customer.png',
				userAvatar: '/static/images/user.png',
				sessionStatus: 0, // 0-活跃 1-已结束

				// 聊天数据
				messageList: [],
				messageContent: '',
				loading: false,
				inputHeight: 40, // 输入框初始高度
				minInputHeight: 40,
				maxInputHeight: 120,

				// WebSocket相关
				stompClient: null,
				reconnectTimer: null,
				reconnectCount: 0,
				maxReconnectCount: 5,

				// 图片预览相关
				previewImageList: []
			};
		},
		onLoad(options) {
			// 从路由参数获取会话ID和客服ID
			this.sessionId = options.sessionId || ''
			this.customerId = options.customerId || ''

			// 如果没有会话ID，创建新会话
			if (!this.sessionId) {
				this.createNewSession()
			} else {
				// 加载历史消息
				this.loadMessageHistory()
				// 连接WebSocket
				this.connectWebSocket()
			}
		},
		onUnload() {
			// 页面卸载时断开连接
			this.disconnectWebSocket()
		},
		methods: {
			/**
			 * 返回上一页
			 */
			navigateBack() {
				uni.navigateBack({
					delta: 1
				})
			},

			/**
			 * 查看会话信息
			 */
			handleSessionInfo() {
				uni.showModal({
					title: '会话信息',
					content: `会话ID: ${this.sessionId}\n状态: ${this.sessionStatus === 0 ? '活跃' : '已结束'}`,
					showCancel: false
				})
			},

			/**
			 * 创建新会话（使用封装的接口）
			 */
			createNewSession() {
				this.loading = true
				createSession()
					.then(res => {
						if (res.code === 200) {
							this.sessionId = res.data
							this.loadMessageHistory()
							this.connectWebSocket()
						} else {
							uni.showToast({
								title: '创建会话失败',
								icon: 'none'
							})
						}
					})
					.catch(() => {
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						})
					})
					.finally(() => {
						this.loading = false
					})
			},

			/**
			 * 重新发起会话
			 */
			restartSession() {
				this.createNewSession()
				this.sessionStatus = 0
			},

			/**
			 * 加载消息历史（使用封装的接口）
			 */
			loadMessageHistory() {
				if (!this.sessionId) return

				this.loading = true
				getCustomerMessageList({ customerSessionId: this.sessionId })
					.then(res => {
						if (res.code === 200) {
							this.messageList = res.rows || []
							this.scrollToBottom()
						} else {
							uni.showToast({
								title: '加载历史消息失败',
								icon: 'none'
							})
						}
					})
					.catch(() => {
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						})
					})
					.finally(() => {
						this.loading = false
					})
			},

			/**
			 * 连接WebSocket
			 */
			connectWebSocket() {
				if (!this.sessionId) return

				// 清除之前的重连计时器
				if (this.reconnectTimer) {
					clearTimeout(this.reconnectTimer)
					this.reconnectTimer = null
				}

				// 构建WebSocket连接地址（使用代理路径）
				const token = getToken()
				const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
				const socketUrl = `${wsProtocol}//${window.location.host}/health-api/chat/ws?token=${token}`

				// 创建SockJS连接
				const socket = new SockJS(socketUrl)
				this.stompClient = Stomp.over(socket)

				// 连接WebSocket
				this.stompClient.connect({},
					// 连接成功回调
					() => {
						console.log('WebSocket连接成功')
						this.reconnectCount = 0

						// 订阅用户接收客服消息的频道
						const userId = this.getUserId()
						this.stompClient.subscribe(`/user/customer/${userId}`, (message) => {
							this.handleReceivedMessage(JSON.parse(message.body))
						})
					},
					// 连接失败回调
					(error) => {
						console.error('WebSocket连接失败:', error)
						this.handleReconnect()
					}
				)
			},

			/**
			 * 处理重连
			 */
			handleReconnect() {
				if (this.reconnectCount < this.maxReconnectCount) {
					this.reconnectCount++
					console.log(`尝试第${this.reconnectCount}次重连...`)

					this.reconnectTimer = setTimeout(() => {
						this.connectWebSocket()
					}, 3000)
				} else {
					uni.showToast({
						title: '连接已断开，请刷新页面重试',
						icon: 'none',
						duration: 3000
					})
				}
			},

			/**
			 * 断开WebSocket连接
			 */
			disconnectWebSocket() {
				if (this.stompClient && this.stompClient.connected) {
					this.stompClient.disconnect()
					console.log('WebSocket已断开连接')
				}

				if (this.reconnectTimer) {
					clearTimeout(this.reconnectTimer)
					this.reconnectTimer = null
				}
			},

			/**
			 * 处理接收到的消息
			 */
			handleReceivedMessage(message) {
				this.messageList.push(message)
				this.scrollToBottom()
			},

			/**
			 * 发送消息
			 */
			sendMessage() {
				if (!this.messageContent.trim() || !this.stompClient || !this.stompClient.connected) return

				// 构建消息对象
				const message = {
					customerSessionId: this.sessionId,
					customerMessageSenderId: this.getUserId(),
					customerMessageSenderType: 2, // 用户
					customerMessageReceiverId: this.customerId,
					customerMessageReceiverType: 3, // 客服
					customerMessageContent: this.messageContent.trim(),
					customerMessageType: 1 // 文本消息
				}

				// 发送消息
				this.stompClient.send("/app/customer/send", {}, JSON.stringify(message))

				// 清空输入框并添加到消息列表
				this.messageList.push({
					...message,
					customerMessageCreateTime: new Date().toISOString()
				})
				this.messageContent = ''
				this.inputHeight = this.minInputHeight
				this.scrollToBottom()
			},

			/**
			 * 选择图片
			 */
			chooseImage() {
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePaths = res.tempFilePaths
						this.uploadImage(tempFilePaths[0])
					}
				})
			},

			/**
			 * 上传图片（使用封装的接口）
			 */
			uploadImage(tempFilePath) {
				// 创建FormData对象
				const formData = new FormData()
				// 注意：不同环境可能需要调整文件对象的构造方式
				formData.append('file', tempFilePath)
				formData.append('sessionId', this.sessionId)
				
				uploadChatImage(formData)
					.then(res => {
						if (res.code === 200) {
							// 上传成功后发送图片消息
							const imageUrl = res.data
							const message = {
								customerSessionId: this.sessionId,
								customerMessageSenderId: this.getUserId(),
								customerMessageSenderType: 2, // 用户
								customerMessageReceiverId: this.customerId,
								customerMessageReceiverType: 3, // 客服
								customerMessageImageUrl: imageUrl,
								customerMessageType: 2 // 图片消息
							}

							this.stompClient.send("/app/customer/send", {}, JSON.stringify(message))
							this.messageList.push({
								...message,
								customerMessageCreateTime: new Date().toISOString()
							})
							this.scrollToBottom()
						} else {
							uni.showToast({
								title: '图片上传失败',
								icon: 'none'
							})
						}
					})
					.catch(() => {
						uni.showToast({
							title: '图片上传失败',
							icon: 'none'
						})
					})
			},

			/**
			 * 预览图片
			 */
			previewImage(url) {
				this.previewImageList = [url]
				uni.previewImage({
					urls: this.previewImageList,
					current: url
				})
			},

			/**
			 * 自动调整输入框高度
			 */
			autoResizeInput(e) {
				const textarea = e.target
				// 重置高度以获取正确的scrollHeight
				textarea.style.height = this.minInputHeight + 'px'
				// 计算新高度
				let newHeight = textarea.scrollHeight
				// 限制高度范围
				if (newHeight < this.minInputHeight) {
					newHeight = this.minInputHeight
				} else if (newHeight > this.maxInputHeight) {
					newHeight = this.maxInputHeight
				}
				// 设置新高度
				this.inputHeight = newHeight
			},

			/**
			 * 滚动到底部
			 */
			scrollToBottom() {
				this.$nextTick(() => {
					const chatContent = this.$refs.chatContentRef
					if (chatContent) {
						chatContent.scrollTop = chatContent.scrollHeight
					}
				})
			},

			/**
			 * 格式化时间
			 */
			formatTime(timeStr) {
				if (!timeStr) return ''

				const date = new Date(timeStr)
				const hours = date.getHours().toString().padStart(2, '0')
				const minutes = date.getMinutes().toString().padStart(2, '0')
				return `${hours}:${minutes}`
			},

			/**
			 * 获取当前用户ID（从Vuex获取）
			 */
			getUserId() {
				return this.$store.state.userId || '';
			}
		}
	};
</script>

<style scoped>
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;
	}

	.navbar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 48px;
		padding: 0 16px;
		background-color: #fff;
		border-bottom: 1px solid #eee;
	}

	.back-btn {
		width: 40px;
		height: 40px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.title {
		font-size: 18px;
		font-weight: 500;
		color: #333;
		flex: 1;
		text-align: center;
	}

	.right-space {
		width: 40px;
		height: 40px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.chat-content {
		flex: 1;
		overflow-y: auto;
		padding: 16px;
		box-sizing: border-box;
	}

	.empty-tip {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 40px 0;
		color: #999;
	}

	.empty-img {
		width: 120px;
		height: 120px;
		margin-bottom: 16px;
	}

	.empty-text {
		font-size: 14px;
	}

	.message-item {
		margin-bottom: 16px;
	}

	.customer-message {
		display: flex;
		align-items: flex-start;
	}

	.user-message {
		display: flex;
		align-items: flex-start;
		justify-content: flex-end;
	}

	.sender-avatar {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		margin-right: 10px;
	}

	.user-message .sender-avatar {
		margin-right: 0;
		margin-left: 10px;
	}

	.message-bubble {
		max-width: 70%;
		padding: 10px 14px;
		border-radius: 18px;
		position: relative;
	}

	.customer-bubble {
		background-color: #fff;
		border: 1px solid #eee;
	}

	.user-bubble {
		background-color: #07c160;
		color: #fff;
	}

	.message-content {
		font-size: 16px;
		line-height: 1.5;
	}

	.message-image {
		width: 100%;
		border-radius: 8px;
	}

	.message-time {
		font-size: 12px;
		color: #999;
		text-align: right;
		margin-top: 4px;
	}

	.user-bubble .message-time {
		color: rgba(255, 255, 255, 0.7);
	}

	.loading-tip {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 16px 0;
		color: #999;
	}

	.loading-text {
		margin-left: 8px;
		font-size: 14px;
	}

	.chat-footer {
		background-color: #fff;
		border-top: 1px solid #eee;
		padding: 8px 16px;
	}

	.tool-bar {
		display: flex;
		padding: 8px 0;
	}

	.tool-item {
		width: 40px;
		height: 40px;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 16px;
	}

	.input-area {
		display: flex;
		align-items: flex-end;
	}

	.message-input {
		flex: 1;
		min-height: 40px;
		max-height: 120px;
		padding: 10px 14px;
		border: 1px solid #eee;
		border-radius: 20px;
		resize: none;
		outline: none;
		font-size: 16px;
	}

	.send-btn {
		width: 60px;
		height: 36px;
		margin-left: 10px;
		background-color: #07c160;
		color: #fff;
		border: none;
		border-radius: 18px;
		font-size: 16px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.send-btn:disabled {
		background-color: #ccc;
	}

	.ended {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 12px 16px;
		font-size: 14px;
		color: #999;
	}

	.ended-icon {
		margin-right: 6px;
	}

	.restart-btn {
		margin-left: 12px;
		color: #07c160;
		background-color: transparent;
		border: 1px solid #07c160;
		border-radius: 16px;
		padding: 4px 12px;
		font-size: 14px;
	}
</style>
